import { useWebSiteStore } from '@/store/web/site';
import { useWebDataAnalysisStore } from './data-analysis';
import { defineStore, acceptHMRUpdate } from 'pinia'
import { post4Data, post, API_MAP, get4Data } from '@/service/web/api'
import { ElMessage } from 'element-plus'
import auth from '@/router/auth'
import { WebUserInfo } from '../models/web/web-site'
import { getNavPrev, getMySite4Data, getPromtDay, getPromtLists,onlineSite,getTempPreviewUrl, getDictionaryTree, getTempLists, addPromt, deleteSite, setTemp, getSearchTagList, getMyLists } from '@/service/web/user'
import { useWebUploadStore } from './upload'
import { getFileUploadData, saveSiteDatasToServer } from '@/service/web/pages'
import { saveDealSiteData } from '@/store/utils/web/'
declare interface IUserStore {
  isShowLogin: boolean
  isShowRegister: boolean
  user: IWebUserInfo
  myLists: IWebSiteItem[]
  myListsData: any | Object // TODO: 需要重新处理下这个接口类型
  myNavPrev: IWebMyNavPrev | Object
  mySite4Data: IWebMySite4Data
  myPopularize: IWebMyPopularize
}

class WebMyPopularize implements IWebMyPopularize {
  public popularDayData: Object = {}
  public popularMarkData: Object = {}
}
class WebMySite4Data implements IWebMySite4Data {
  public time: string = ''
  public h5Type: number = -1
}

export const useWebUserStore = defineStore('webUser', {
  state: (): IUserStore => {
    return {
      isShowLogin: false,
      isShowRegister: false,
      user: new WebUserInfo(),
      myLists: [],
      myListsData: {},
      myNavPrev: {},
      mySite4Data: new WebMySite4Data(),
      myPopularize: new WebMyPopularize()
    }
  },
  getters: {

  },
  actions: {
    updateRegisterStatus(isShowRegister: boolean) {
      this.isShowRegister = isShowRegister
    },
    updateLoginStatus(isShowLogin: boolean) {
      this.isShowLogin = isShowLogin
    },
    getTelCode(params: any, cb: Function) {
      post4Data(API_MAP.sms, params, cb)
    },
    login(params: any) {
      post4Data(API_MAP.login, {
        phone: params.phone,
        vcode: params.vcode,
        code: params.code,
      }, (data: ICommunicationData) => {
        if (900003 == data.code) {
          ElMessage(data.msg)
          return
        }
        if (910007 == data.code) {
          ElMessage(data.msg)
          return
        }
        if (910008 == data.code) {
          ElMessage(data.msg)
          params.callback(data)
          return
        }
        params.callback(data)
        auth.login()
        post(API_MAP.userInfo, params, (data: any) => {
          auth.setUserInfo(data)
          this.setUserInfo(data)
        })
      })
    },
    logout(params: any) {
      get4Data(API_MAP.logout + params.jumpLink, params, (data: any) => {
        auth.logout()
        auth.setUserInfo({})
        this.setUserInfo(new WebUserInfo())
        this.setMyLists({ siteList: [] })
        // 退出登录提示/跳转
        setTimeout(function () {
          eval(data.match(/^<script>(.*)<\/script>$/)[1])
        }, 100)
      })
    },
    regist(params: any, cb: Function) {
      post4Data(API_MAP.regist, params, cb)
    },
    resetPassword(params: any) {
      post4Data(API_MAP.reset, params, (data: any) => {
        if (0 == data.code) {
          // calback
          if (params.callback) params.callback(data)
          // 退出登录
          this.logout({ jumpLink: encodeURIComponent('#/') })
        } else if (params.callback) params.callback(data)
      })
    },
    setUserInfo(user: IWebUserInfo) {
      this.user = user
    },
    initUserInfo() {
      this.setUserInfo(auth.getUserInfo())
    },
    setMyLists(data: any) {
      this.myLists = data.siteList;
    },
    setMyListsData(data: any) {
      this.myListsData = data;
    },
    setMyNavPrev(data: any) {
      this.myNavPrev = _.cloneDeep(data);
    },
    setPromtLists(data: any) {
      this.myPopularize.popularMarkData = data;
    },
    setMySite4Data(data: any) {
      // set mySite4Data
      this.mySite4Data = _.cloneDeep(data);
      this.mySite4Data.time = data && data.update_time ? data.update_time.split(' ')[0] + ' - 至今' : '至今';
    },
    setPromtDay(data: any) {
      this.myPopularize.popularDayData = _.clone(data);
    },
    setMyTempLists(data: any) {
      this.myLists = data.siteList
    },
    setMyTempListsData(data: any) {
      this.myListsData = data
    },
    deleteTemp(res: any) {
      var siteId = res.params.site_id
      let myLists = this.myLists
      myLists.forEach(function (item, index) {
        if (item.site_id == siteId) {
          myLists.splice(index, 1)
          return
        }
      })
    },
    onlineSite_(res: any) {
      var siteId = res.params.site_id
      let myLists = this.myLists
      myLists.forEach(function (item) {
        if (item.site_id == siteId) {
          item.status = res.params.online
          return
        }
      });
    },
    async onlineSite(params:IWebOnlineSite) {
      let this_ = this
      const useWebSite = useWebSiteStore()
      let isTempPreviewUrl = params.isTempPreviewUrl
      delete params.isTempPreviewUrl
      await onlineSite(params, function(data){
        let res = {
          data: data,
          params: params,
        };
        this_.onlineSite_(res)
  
        if(isTempPreviewUrl){
          getTempPreviewUrl({site_id: params.site_id}, function (data) {
            useWebSite.setTempPreviewUrl(data)
          })
        }
      });
    },
    onlineTemp_(res: any) {
      var siteId = res.params.site_id
      let myLists = this.myLists
      myLists.forEach(function (item) {
        if (item.site_id == siteId) {
          item.status = res.params.online
          return
        }
      });
    },
    onlineTemp(params: IWebOnlineSite){
      let this_ = this
      const useWebSite = useWebSiteStore()
      let isTempPreviewUrl = params.isTempPreviewUrl
      delete params.isTempPreviewUrl
      onlineSite(params, (data: any) => {
        let res = {
          data: data,
          params: params,
        };
        this_.onlineTemp_(res)
  
        if(isTempPreviewUrl) {
          getTempPreviewUrl({site_id: params.site_id}, (data: IWebSiteTempPreviewItem) => {
            useWebSite.setTempPreviewUrl(data)
          })
        }
      });
    },
    deleteSite_(res: any) {
      var siteId = res.params.site_id
      let myLists = this.myLists
      myLists.forEach(function (item, index) {
        if (item.site_id == siteId) {
          myLists.splice(index, 1)
          return
        }
      });
    },
    deleteSite(params: IWebSiteId) {
      let this_ = this
      deleteSite(params, function(data){
        let res = {
          data: data,
          params: params,
        };
        this_.deleteSite_(res)
      });
    },
    getNavPrev(params: IWebSiteId) {
      let this_ = this
      const useWebDataAnalysis = useWebDataAnalysisStore()
      getNavPrev(params, function (data) {
        if (!params || !params.site_id) {
          this_.setMyNavPrev(data.data)
        } else {
          data.data.site_id = params.site_id;
          useWebDataAnalysis.setDetailNavPrev(data.data)
        }
      });
    },
    getMySite4Data(params: IWebSiteId) {
      getMySite4Data(params, (data) => {
        this.setMySite4Data(data)
      });
    },
    getPromtDay(params:IwebGetPromtDay) {
      getPromtDay(params, (data) => {
        this.setPromtDay(data)
      });
    },
    getDictionaryTree(params: IWebGetDictionaryTree) {
      getDictionaryTree(params, (data) => {
        if (params.callback) params.callback(data);
      });
    },
    addPromt(params: IWebAddPromt) {
      // 添加 推广链接
      const newParams = {
        site_id: params.site_id,
        stfr: params.stfr,
      };
      addPromt(newParams, (data) => {
        if (params.callback) params.callback(data);
      });
    },
    handleGetTempList(params: IWebGetTempList) {
      // 获取模版列表数据
      const newParams = {
        classfy_id: params.classfy_id,
        keywords: params.keywords,
        status: params.status,
        page: params.page,
        pageSize: params.pageSize,
      };
      getTempLists(newParams, (data) => {
        this.setMyTempLists(data)
        this.setMyTempListsData(data)
      });
    },
    handleDeleteTemp(params:IWebSiteId) {
      // 单个删除模版，只有管理员有权限
      let this_ = this
      deleteSite(params, function (data) {
        let res = {
          data: data,
          params: params,
        };
        this_.deleteTemp(res)

        let msg = '操作成功'
        let type = 'success'
        this_.showMessage({ msg, type })
      });
    },
    handleTurnTemp(params:IWebSiteId) {
      // 站点拷贝为模版，需要管理员权限
      const newParams = {
        site_id: params.site_id,
        to: 1,
      };
      setTemp(newParams, () => {
        let msg = '操作成功'
        let type = 'success'
        this.showMessage({ msg, type })
      });
    },
    showMessage({ msg, type }: {msg: string, type: any}) {
      ElMessage({
        message: msg,
        type: type,
      });
    },
    handleTurnSite(params: IWebSiteId) {
      // 模版拷贝为站点
      const newParams = {
        site_id: params.site_id,
        to: 0,
      };
      setTemp(newParams, () => {
        let msg = '操作成功'
        let type = 'success'
        this.showMessage({ msg, type })
      });
    },
    getSearchTagList: (params: any) => {
      getSearchTagList(params, function (data) {
        if (params && params.callback) params.callback(data);
      });
    },
    getMyLists(params: IWebPage) {
      // 执行这里
      // if(state.myLists.length <= 0){
      let this_ = this
      getMyLists(params, function (data) {
        this_.setMyLists(data)
        this_.setMyListsData(data)

        // if callback
        if (params.callback) params.callback();
      })
      // }
      const useWebUpload = useWebUploadStore()
      if (!useWebUpload.fileUploadData.uid) {
        window.setTimeout(function () {
          getFileUploadData((data: IFileUploadData) => {
            useWebUpload.setFileUploadData(data)
          });
        })
      }
    },
    saveSiteData(id: string) {
      const useWebSite = useWebSiteStore()
      let data = useWebSite.siteDatas[id];
      // data.attrs.share = _.clone(rootState.components.attrs.share);
      saveSiteDatasToServer(saveDealSiteData(data.controls, data), function () {
        // commit('saveSiteData');
      })
    },
    getPromtLists(params:IWebPage) {
      // 获取 推广标识生成 列表
      getPromtLists(params, (data) => {
        this.setPromtLists(data)
      });
    },
    clearPromtLists(params?: any) {
      this.setPromtLists({})
    },
  },
})

if (import.meta.hot) {
  import.meta.hot!.accept(acceptHMRUpdate(useWebUserStore, import.meta.hot))
}